package com.kawins.supers.message.socket.util;

import com.alibaba.fastjson.JSON;
import com.kawins.supers.message.socket.bean.SocketMessage;
import com.kawins.supers.message.socket.manager.WebSocketBank;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * @author rankai
 *         createTime 2017-10-2017/10/30 17:31
 */
public class WebSocketKit {

    /**
     * 清除某人的socket
     *
     * @param key
     * @param sessionId
     */
    public static void closeWebSocket(Serializable key, Serializable sessionId) {
        if (key != null) {
            WebSocketSession webSocketSession = WebSocketBank.get(key, sessionId);
            if (webSocketSession != null) {
                try {
                    webSocketSession.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 清除某人的socket
     *
     * @param key
     */
    public static void closeWebSocket(Serializable key) {
        if (key != null) {
            List<WebSocketSession> webSocketSessions = WebSocketBank.get(key);
            if (webSocketSessions != null) {
                for (WebSocketSession webSocketSession : webSocketSessions) {
                    try {
                        webSocketSession.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 清除全部socket
     */
    public static void closeAll() {
        List<WebSocketSession> sessions = WebSocketBank.getAll();
        if (sessions != null) {
            try {
                for (WebSocketSession session : sessions) {
                    session.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送消息
     *
     * @param socketSession
     * @param message
     */
    public static void send(WebSocketSession socketSession, SocketMessage message) {
        if (socketSession != null && message != null) {
            try {
                socketSession.sendMessage(new TextMessage(JSON.toJSONString(message)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param message
     * @param message
     */
    public static void sendAll(SocketMessage message) {
        List<WebSocketSession> sessions = WebSocketBank.getAll();
        for (WebSocketSession session : sessions) {
            send(session, message);
        }
    }
}
